package util

import (
	"fmt"
	"net"
	"os/exec"
	"runtime"
	"strings"
)

func OpenBrowser(url string) {
	var cmd *exec.Cmd
	switch runtime.GOOS {
	case "linux":
		cmd = exec.Command("xdg-open", url)
	case "windows":
		cmd = exec.Command("rundll32", "url.dll,FileProtocolHandler", url)
	case "darwin":
		cmd = exec.Command("open", url)
	}
	if cmd == nil {
		return
	}
	_ = cmd.Start()
}

func GetIpAndMAC() (string, string, error) {
	// 获取所有网络接口
	interfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println("Error fetching interfaces:", err)
		return "", "", err
	}

	ips := ""
	macs := ""
	for _, iface := range interfaces {
		// 跳过无效的接口
		if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
			continue
		}

		if strings.Contains(iface.Name, "VMware Network Adapter") || strings.Contains(iface.Name, "vEthernet") {
			continue
		}
		desc := GetInterfaceDescriptionByName(iface.Name)
		if strings.Contains(desc, "VirtualBox Host-Only Ethernet Adapter") {
			continue
		}

		// 获取接口的地址信息
		addrs, err := iface.Addrs()
		if err != nil {
			fmt.Printf("Error fetching addresses for interface %s: %v\n", iface.Name, err)
			continue
		}

		for _, addr := range addrs {
			// 检查地址类型，只处理 IPv4
			var ip net.IP
			switch v := addr.(type) {
			case *net.IPNet:
				ip = v.IP
			case *net.IPAddr:
				ip = v.IP
			}

			// 跳过无效或非 IPv4 的地址
			if ip == nil || ip.IsLoopback() || ip.To4() == nil {
				continue
			}
			desc := GetInterfaceDescriptionByMAC(iface.HardwareAddr.String())
			if strings.Contains(desc, "VirtualBox Host-Only Ethernet Adapter") {
				continue
			}

			if ips == "" {
				ips = ip.String()
			} else {
				ips = ips + "\n" + ip.String()
			}
			if macs == "" {
				macs = iface.HardwareAddr.String()
			} else {
				macs = macs + "\n" + iface.HardwareAddr.String()
			}
		}
	}
	return ips, macs, nil
}

func PadLeft(input string, length int, padChar rune) string {
	padding := length - len(input)
	if padding > 0 {
		padStr := strings.Repeat(string(padChar), padding)
		return padStr + input
	}
	return input
}
